Jersey/Jackson Polymorphic Deserialization

Categories: Java; Tagged with: ; @ October 1st, 2013 20:56

Jersey can handle concrete data binding smoothly, however, for Polymorphic, it’s not very configurable.

e.g.:

IUser

DefaultUser, SGUser, CNUser

We need a web service, which accept POST request from Client side:

saveUser(IUser newUser)…

Nobody knows it’s a DefaultUser or SGUser, or CNUser, except Spring config XML.  and there’re some ways to use Jersey do the deserialization.:

http://programmerbruce.blogspot.sg/2011/05/deserialize-json-with-jackson-into.html

 

However, I prefer to use “Simple” Data Binding from Jackson to do the mapping manually:

“Simple here just means that range of value types is limited to core JDK types”

  Object root = mapper.readValue(src, Object.class);
  Map<?,?> rootAsMap = mapper.readValue(src, Map.class);
 

So in the saveUser() method, we can get the raw values and then initialize the instances with the help of Spring to make sure what we know and what we only need to know is ‘Interface’/Contract:

saveUser(Map<String, Object> json) {

(Cast) json.get(“key”);

}

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.